package 滑动窗口;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class 字符串中所有字母异位词 {
    public List<Integer> findAnagrams(String s2, String s1) {
        List<Integer> list = new ArrayList<>();
        Map<Character, Integer> window = new HashMap<>();
        Map<Character, Integer> need = new HashMap<>();
        for (int i = 0; i < s1.length(); i++) {
            need.put(s1.charAt(i),need.getOrDefault(s1.charAt(i),0)+1);
        }
        int left=0;
        int right=0;
        int vaild=0;
        while (right<s2.length()){
            char c = s2.charAt(right);
            right++;
            //更新右侧窗口
            if (need.containsKey(c)){
                window.put(c,window.getOrDefault(c,0)+1);
                if (window.get(c).equals(need.get(c)))
                    vaild++;
            }
            //更新左侧窗口
            while (right-left>=s1.length()){
                if (vaild==need.size())
                    list.add(left);
                char c1 = s2.charAt(left);
                left++;
                if (need.containsKey(c1)){
                    if (window.get(c1).equals(need.get(c1)))
                        vaild--;
                    window.put(c1,window.getOrDefault(c1,0)-1);
                }
            }
        }
        return list;
    }
}
